<?php
/*
	Class: Blog_IndexController

	About: Author
		Jaybill McCarthy

	About: License
		<http://communit.as/docs/license>
*/
class Blog_IndexController extends Cts_Controller_Action_Abstract {
	
	function indexAction() {
		$request = new Cts_Request($this->getRequest());
		$posts_table = new BlogPosts();
		$posts_table->memCacheOn();
		$comments_table = new BlogComments();
		$comments_table->memCacheOn(); 
		$cats_table = new BlogViewPostsCategories();
		$cats_table->memCacheOn();
		$tmp_posts = array();
				
		if ($request->has("year") and $request->has("month")) {			
			$posts = $posts_table->fetchByMonth($request->month,$request->year);
			$this->view->month = $request->month;
			$this->view->year = $request->year;
			$this->view->selected_month_date = strtotime($request->month."/1/".$request->year);	
		} else {
			$posts = $posts_table->fetchAllActive("publish_on desc", Cts_Registry::get("posts_on_index_page","blog"));
		}		

		if (count($posts) > 0) {
			$posts = $posts_table->prepareRowsetForView($posts);
			foreach ($posts as $post) {
				$tmp_post = $post;
				$where = $cats_table->getAdapter()->quoteInto("post_id = ?", $tmp_post['id']);
				$tmp_cats = $cats_table->fetchAllArray($where);
				$cats = array();
				foreach ($tmp_cats as $cat) {
					$tmp_cat = $cat;
					$cat_slug_split = explode("-", $cat['category_slug']);
					$tmp_cat['activity'] = $cat_slug_split[0];
					$tmp_cat['subsection'] = $cat_slug_split[1];
					$cats[] = $tmp_cat;
				}
				$tmp_post['filed_under'] = $cats;
				$tmp_posts[] = $tmp_post;
			}
			$this->view->posts = $tmp_posts;
		}
		$this->view->months_with_posts = $posts_table->getMonthsWithPosts(null, false, true);
		
		$recent_comments = $comments_table->getRecentArray(Cts_Registry::get('recent_comments_per_page', 'blog'));		
		if (count($recent_comments) > 0) {			
			$this->view->recent_comments = $recent_comments;
		}
	}

	function archiveAction() {
		$posts_table = new BlogPosts();
		$posts_table->memCacheOn();
		$this->view->months_with_posts = $posts_table->getMonthsWithPosts(null, false, false);
		$additional = $this->_cts_plugin->doFilter($this->_mca, array()); // FILTER HOOK
		foreach ($additional as $key => $value) {
			$this->view->$key = $value;
		}
	}

	function viewAction() {
		$this->_displayPost();
	}

	function previewAction() {
		$this->_displayPost(true);
	}

	private function _displayPost($showInactive = false) {
		$request = new Cts_Request($this->getRequest());
		$posts_table = new BlogPosts();
		$posts_table->memCacheOn();
		$categories_table = new BlogCategories();
		$categories_table->memCacheOn();
		$categories_tags_table = new BlogCategoriesTags();
		$categories_tags_table->memCacheOn();
		$comments_table = new BlogComments();
		$users_table = new Users();

		if ($request->has("slug")) {
			$post = $posts_table->fetchBySlug($request->slug, $showInactive);
			if (is_null($post)) {
				$this->_redirect("/default/auth/missing");
			}	
		}

		if ($request->has('activity')) {
			$this->view->activity = $request->activity;
		}
		if ($request->has('subsection')) {
			$this->view->subsection = $request->subsection;
		}

		$post = $posts_table->preparePostForView($post);
		
		if( isset($post['title']) ){
			$post['title_stripped'] = strip_tags($post['title']);
		}
							
		$this->view->post = $post;
		//$similar_posts = $posts_table->fetchSimilarById($post['id'], false, Cts_Registry::get('similar_posts_on_view_page', 'blog'));
		
		$category_slugs = $categories_table->getCategorySlugsByPostId($post['id']);
		
		$similar_posts = $posts_table->fetchAllByCategorySlugs($category_slugs, false, Cts_Registry::get('similar_posts_on_view_page', 'blog'), null, "all");		
					
		if (count($similar_posts) > 0) {
			$similar_posts = $posts_table->prepareRowsetForView($similar_posts);
			
			foreach($similar_posts as $index => $similar_post){
				if($similar_post['id'] == $post['id']){
					unset($similar_posts[$index]);
				}
			}			
				 					
		} 	


		if (count($similar_posts) == 0) { //if there's nothing left from the last attempt to go by category slug, try splitting the slug into cats and get data in from those cats as tags

			$category_ids = $categories_table->getCategoryIdsByPostId($post['id']);
			$similar_tags = array();
			foreach($category_ids as $cat_id){
				$similar_tags = array_merge($categories_tags_table->getTagsByCategoryId($cat_id),$similar_tags);
			}

			$similar_posts = $posts_table->fetchAllByTags($similar_tags, false, Cts_Registry::get('similar_posts_on_view_page', 'blog'), null, "any");			
		
			if (count($similar_posts) > 0) {
				$similar_posts = $posts_table->prepareRowsetForView($similar_posts);

				foreach($similar_posts as $index => $similar_post){
					if($similar_post['id'] == $post['id']){
						unset($similar_posts[$index]);
					}
				}			

			} 	
		}			
		
		if (count($similar_posts) > 0) {
			
			$similar_posts = array_slice ( $similar_posts, 0 , Cts_Registry::get('similar_posts_on_view_page', 'blog'), false );
			$this->view->similar_posts = $similar_posts;	
		}	
						
		
		$recent_comments = $comments_table->getRecentArray(Cts_Registry::get('recent_comments_per_page', 'blog'));
		if (count($recent_comments) > 0) {
			$this->view->recent_comments = $recent_comments;
		}
		
		$comments = $comments_table->fetchAll($comments_table->select()->where("post_id = ?", $post['id'])->where("active = 1"));
		if (count($comments) > 0) {
			$this->view->comments = $comments_table->prepareRowsetForView($comments);
		}
		
		if ($this->getRequest()->isPost()) {
			$request = new Cts_Request($this->getRequest());
			$request->stripTags(array("comment_full_name","comment_email","comment_body"));
			
			if (!$this->_auth->hasIdentity()) {
				$request->addValidator("comment_full_name", $this->_T("Please enter your name."));			
				$request->addValidator("comment_email", $this->_T("Please enter your email. It will not be shown."));
			}
			$request->addValidator("comment_body", $this->_T("You did not enter a comment."));
			
			$errors = array();
			
			if (!$request->isValid()) {
				$errors = $request->getValidationErrors();
			};
						
			$comments_table = new BlogComments();
			$modules_table = new Modules();
			//$useWorkflow = $modules_table->isEnabled("workflow");
			$useWorkflow = false;

			if (count($errors) == 0) {
				$data = array(
		  	 		"post_id" 		=> $post['id'],
		  			"created_on" 	=> date(DB_DATETIME_FORMAT),
		  			"publish_on"	=> date(DB_DATETIME_FORMAT),
		  			"body"			=> $request->comment_body,
		  		);

		  		if ($this->_auth->hasIdentity()) {
		  			$comment_user = $users_table->fetchByUsername($this->_identity->username);
		  			if (!is_null($comment_user)) {
		  				$data['author_username'] 	= $comment_user->username;
		  				$data['author_full_name']	= $comment_user->full_name;
		  				$data['author_email']		= $comment_user->email;
		  			} 
		  		} else {  				
		  				$data['author_full_name']	= $request->comment_full_name;
		  				$data['author_email']		= $request->comment_email;
		  		}

		  		// if ($useWorkflow) {
		  		// 	$data['active'] = 0;
		  		// } else {
		  		// 	$data['active'] = 1;
		  		// }
	  			$data['active'] = 0;

		  		$id = $comments_table->insert($data);
		  		$this->_redirect("/journal/".$request->activity."/".$request->subsection."/".$post['slug']."#comment-".$id);
			} else {
				$this->view->errors = $errors;
				if (!$this->_auth->hasIdentity()) {
					$this->view->comment_full_name = $request->comment_full_name;
					$this->view->comment_email	 = $request->comment_email;
				}
				$this->view->comment_body = $request->comment_body;
				
			}
		}		
	}
	
}
